package conceptmaniax.hotelapp.activities;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import conceptmaniax.hotelapp.config.Constants;
import conceptmaniax.hotelapp.util.database.DataHelper;
import conceptmaniax.hotelapp.util.sync.FileSyncUtils;
import conceptmaniax.hotelapp.activities.R;

public class SplashScreenActivity extends Activity {
    
	private DataHelper dataHelper = new DataHelper(this, Constants.DATABASE_NAME);
	private DataHelper dataHelperRequest = new DataHelper(this, Constants.REQUEST_DATABASE_NAME);

	/** Called when the activity is first created. */
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        
        final Thread splashTimer = new Thread(){
        	public void run(){
        		try{
        			// sleep 2
        			Thread.sleep(2000);
        			
        			final SharedPreferences settings = getSharedPreferences(Constants.APP_NAME, 0);
        			final SharedPreferences.Editor editor = settings.edit();
        			
        			// content version
        			final String contentVersionFromApp = settings.getString(Constants.CONTENT_VERSION_NAME, null);
        			if (contentVersionFromApp == null) {
        				editor.putString(Constants.CONTENT_VERSION_NAME, Constants.APP_STORE_CONTENT_VERSION);
        				editor.commit();
        			}
        			
        			// language preferences settings
        			boolean firstrun = settings.getBoolean("FirstRun",true);
        			if (firstrun) {
        				editor.putBoolean("FirstRun", false);
        				editor.commit();
        				
        				dataHelper.copyDataBaseFromAssets();
        				dataHelperRequest.copyDataBaseFromAssets();
        				FileSyncUtils.copyImagesFromAssets(SplashScreenActivity.this);

        				final Intent LanguageSelectionIntent = new Intent(Constants.LANGUAGE_ACTIVITY);
        				startActivity(LanguageSelectionIntent);
        			} else {
        				final Intent homePageIntent = new Intent(Constants.HOMEPAGE_ACTIVITY);
        				startActivity(homePageIntent);
        			}
        			
        		} catch (InterruptedException ie) {
				} catch (Exception e) {
    			} finally {
    				SplashScreenActivity.this.finish();
        		}
        	}
        };
        splashTimer.start();
    }
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if ( dataHelper != null ) {
			dataHelper.close();
		}
		if ( dataHelperRequest != null ) {
			dataHelperRequest.close();
		}
	}
}